package util

import (
	"d-serv-go/server/core/log"
	"time"
)

var DateUtil = newDateUtil()

type dateUtil struct {
}

func newDateUtil() *dateUtil {
	return &dateUtil{}
}

const (
	/*** 系统总的失效日期. */
	DATE_FOREVER = "9999-12-31"
	/** 时间格式. */
	FORMAT_DATETIME = "2006-01-02 15:04:05"
	/** 时间格式. */
	FORMAT_DATE_CN = "2006年01月02日"
	/** 时间格式. */
	FORMAT_TIMESTAMP = "2006-01-02 15:04:05:121"
	/** 到小时分钟的日期格式. */
	FORMAT_DATETIME_HM = "2006-01-02 15:04"
	/** 全时间格式. */
	FORMAT_FULLTIME = "160211121212121"
	/** 日期格式. */
	FORMAT_DATE = "2006-01-02"
	/** 日期格式. */
	FORMAT_YEARMONTH = "2006-01"
	/** 纯时间格式. */
	FORMAT_TIME = "12:12:11"
)

func (u dateUtil) GetDateFromString(s string) string {
	var format string
	switch len(s) {
	case 19:
		format = FORMAT_DATETIME
		break
	case 24:
		format = FORMAT_TIMESTAMP
		break
	default:
		format = FORMAT_DATE
	}
	return GetDateFromString(s, format)

}

func (u dateUtil) GetTime(s string) *time.Time {
	var format string
	switch len(s) {
	case 19:
		format = FORMAT_DATETIME
		break
	case 24:
		format = FORMAT_TIMESTAMP
		break
	default:
		format = FORMAT_DATE
	}
	return GetTimeFormat(s, format)
}

func GetTimeFormat(s string, format string) *time.Time {
	t, err := time.ParseInLocation(format, s, time.Local)
	if err != nil {
		log.Error("Dateutil.GetDateFromString异常了 %v", err)
		return nil
	}
	return &t
}

func (u dateUtil) Before(begin, end string) bool {
	b := u.GetTime(begin)
	e := u.GetTime(end)
	return b.Nanosecond() < e.Nanosecond()
}

func (u dateUtil) GetDatetimeTS() string {
	return time.Now().Format("2006-01-02 15:04:05.000")
}

func GetDateFromString(s string, layout string) string {
	t, err := time.ParseInLocation(layout, s, time.Local)
	if err != nil {
		log.Error("Dateutil.GetDateFromString异常了 %v", err)
		return ""
	}
	return t.Format(layout)
}

func (u dateUtil) GetDateTime() string {
	return time.Now().Format(FORMAT_DATETIME)
}
